{% extends "base.html" %}

{% block title %}个人中心 - 个人工具网站集{% endblock %}

{% block content %}
<div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <!-- 页面标题 -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900">
                <i class="fas fa-user-circle text-blue-600 mr-3"></i>个人中心
            </h1>
            <p class="mt-2 text-gray-600">管理您的账户信息和上传的工具</p>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
            <!-- 左侧导航 -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="text-center mb-6">
                        <div class="w-20 h-20 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-user text-blue-600 text-2xl"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray-900">{{ current_user.username if current_user else '用户' }}</h3>
                        <p class="text-sm text-gray-500">{{ current_user.email if current_user else 'user@example.com' }}</p>
                        <div class="mt-2">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                <i class="fas fa-check-circle mr-1"></i>已验证
                            </span>
                        </div>
                    </div>
                    
                    <nav class="space-y-2">
                        <a href="#" onclick="showTab('overview', event)" 
                           class="nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-blue-600 bg-blue-50 border border-blue-200">
                            <i class="fas fa-tachometer-alt mr-3"></i>概览
                        </a>
                        <a href="#" onclick="showTab('upload', event)" 
                           class="nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-700 hover:bg-gray-100">
                            <i class="fas fa-upload mr-3"></i>上传工具
                        </a>
                        <a href="#" onclick="showTab('tools', event)" 
                           class="nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-700 hover:bg-gray-100">
                            <i class="fas fa-tools mr-3"></i>我的工具
                        </a>
                        <a href="#" onclick="showTab('settings', event)" 
                           class="nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-700 hover:bg-gray-100">
                            <i class="fas fa-cog mr-3"></i>账户设置
                        </a>
                        <a href="#" onclick="showTab('security', event)" 
                           class="nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-700 hover:bg-gray-100">
                            <i class="fas fa-shield-alt mr-3"></i>安全设置
                        </a>
                    </nav>
                </div>
            </div>
            
            <!-- 右侧内容 -->
            <div class="lg:col-span-3">
                <!-- 概览标签页 -->
                <div id="overview-tab" class="tab-content">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                        <i class="fas fa-upload text-blue-600 text-xl"></i>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-gray-500">上传工具数</p>
                                    <p class="text-2xl font-bold text-gray-900" id="uploadedToolsCount">0</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                                        <i class="fas fa-eye text-green-600 text-xl"></i>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-gray-500">总访问量</p>
                                    <p class="text-2xl font-bold text-gray-900" id="totalViews">0</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                                        <i class="fas fa-star text-purple-600 text-xl"></i>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-medium text-gray-500">获得点赞</p>
                                    <p class="text-2xl font-bold text-gray-900" id="totalLikes">0</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 最近活动 -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
                        <h3 class="text-lg font-semibold text-gray-900 mb-4">
                            <i class="fas fa-clock text-gray-500 mr-2"></i>最近活动
                        </h3>
                        <div class="space-y-4" id="recentActivity">
                            <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                                <div class="flex-shrink-0 w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-upload text-blue-600 text-sm"></i>
                                </div>
                                <div class="ml-3 flex-1">
                                    <p class="text-sm font-medium text-gray-900">上传了新工具</p>
                                    <p class="text-sm text-gray-500">2小时前</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 热门工具 -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <h3 class="text-lg font-semibold text-gray-900 mb-4">
                            <i class="fas fa-fire text-orange-500 mr-2"></i>我的热门工具
                        </h3>
                        <div class="space-y-3" id="popularTools">
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                                        <i class="fas fa-tools text-green-600 text-sm"></i>
                                    </div>
                                    <div class="ml-3">
                                        <p class="text-sm font-medium text-gray-900">暂无工具</p>
                                        <p class="text-sm text-gray-500">上传您的第一个工具</p>
                                    </div>
                                </div>
                                <div class="text-sm text-gray-500">
                                    <i class="fas fa-eye mr-1"></i>0
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 上传工具标签页 -->
                <div id="upload-tab" class="tab-content hidden">
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <h3 class="text-lg font-semibold text-gray-900 mb-6">
                            <i class="fas fa-upload text-blue-600 mr-2"></i>上传HTML工具
                        </h3>
                        
                        <form id="uploadForm" enctype="multipart/form-data" class="space-y-6">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label for="toolName" class="block text-sm font-medium text-gray-700 mb-2">
                                        <i class="fas fa-tag mr-2"></i>工具名称
                                    </label>
                                    <input type="text" id="toolName" name="tool_name" required 
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                           placeholder="请输入工具名称">
                                </div>
                                
                                <div>
                                    <label for="toolCategory" class="block text-sm font-medium text-gray-700 mb-2">
                                        <i class="fas fa-folder mr-2"></i>工具分类
                                    </label>
                                    <select id="toolCategory" name="category" required 
                                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <option value="">请选择分类</option>
                                        <option value="开发助手">开发助手</option>
                                        <option value="图像工具">图像工具</option>
                                        <option value="文档处理">文档处理</option>
                                        <option value="小游戏">小游戏</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div>
                                <label for="toolDescription" class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-align-left mr-2"></i>工具描述
                                </label>
                                <textarea id="toolDescription" name="description" rows="3" 
                                          class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                          placeholder="请简要描述工具的功能和用途"></textarea>
                            </div>
                            
                            <!-- 文件上传区域 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-file-code mr-2"></i>HTML文件
                                </label>
                                <div class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-400 transition-colors cursor-pointer"
                                     onclick="document.getElementById('htmlFile').click()">
                                    <div id="uploadPlaceholder">
                                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                                        <p class="text-lg font-medium text-gray-600 mb-2">点击上传或拖拽文件到此处</p>
                                        <p class="text-sm text-gray-500">支持 .html 文件，最大 10MB</p>
                                    </div>
                                    <div id="uploadPreview" class="hidden">
                                        <i class="fas fa-file-code text-4xl text-blue-500 mb-4"></i>
                                        <p class="text-lg font-medium text-gray-900 mb-2" id="fileName"></p>
                                        <p class="text-sm text-gray-500" id="fileSize"></p>
                                        <button type="button" onclick="clearFile()" class="mt-2 text-red-600 hover:text-red-800">
                                            <i class="fas fa-times mr-1"></i>移除文件
                                        </button>
                                    </div>
                                </div>
                                <input type="file" id="htmlFile" name="html_file" accept=".html" class="hidden" onchange="handleFileSelect(this)">
                            </div>
                            
                            <!-- 标签 -->
                            <div>
                                <label for="toolTags" class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-tags mr-2"></i>标签 (可选)
                                </label>
                                <input type="text" id="toolTags" name="tags" 
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                       placeholder="用逗号分隔多个标签，如：工具,实用,免费">
                                <p class="text-sm text-gray-500 mt-1">标签有助于其他用户发现您的工具</p>
                            </div>
                            
                            <!-- 隐私设置 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-3">
                                    <i class="fas fa-eye mr-2"></i>隐私设置
                                </label>
                                <div class="space-y-3">
                                    <label class="flex items-center">
                                        <input type="radio" name="privacy" value="public" checked 
                                               class="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500">
                                        <span class="ml-3 text-sm text-gray-700">
                                            <i class="fas fa-globe mr-2 text-green-500"></i>公开 - 所有人都可以访问
                                        </span>
                                    </label>
                                    <label class="flex items-center">
                                        <input type="radio" name="privacy" value="private" 
                                               class="h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500">
                                        <span class="ml-3 text-sm text-gray-700">
                                            <i class="fas fa-lock mr-2 text-red-500"></i>私有 - 仅您可以访问
                                        </span>
                                    </label>
                                </div>
                            </div>
                            
                            <!-- 提交按钮 -->
                            <div class="flex justify-end space-x-4">
                                <button type="button" onclick="resetForm()" 
                                        class="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                                    <i class="fas fa-undo mr-2"></i>重置
                                </button>
                                <button type="submit" id="uploadBtn" 
                                        class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                    <span id="uploadText">
                                        <i class="fas fa-upload mr-2"></i>上传工具
                                    </span>
                                    <span id="uploadLoading" class="hidden">
                                        <i class="fas fa-spinner fa-spin mr-2"></i>上传中...
                                    </span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- 我的工具标签页 -->
                <div id="tools-tab" class="tab-content hidden">
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <div class="flex justify-between items-center mb-6">
                            <h3 class="text-lg font-semibold text-gray-900">
                                <i class="fas fa-tools text-blue-600 mr-2"></i>我的工具
                            </h3>
                            <div class="flex space-x-3">
                                <select id="sortBy" class="px-3 py-2 border border-gray-300 rounded-lg text-sm">
                                    <option value="created_desc">最新上传</option>
                                    <option value="views_desc">访问量最高</option>
                                    <option value="name_asc">名称排序</option>
                                </select>
                                <button onclick="refreshTools()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm">
                                    <i class="fas fa-sync-alt mr-2"></i>刷新
                                </button>
                            </div>
                        </div>
                        
                        <div id="toolsList" class="space-y-4">
                            <!-- 工具列表将通过JavaScript动态加载 -->
                            <div class="text-center py-12">
                                <i class="fas fa-tools text-4xl text-gray-300 mb-4"></i>
                                <p class="text-gray-500">暂无上传的工具</p>
                                <button onclick="showTab('upload', event)" class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                    <i class="fas fa-plus mr-2"></i>上传第一个工具
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 账户设置标签页 -->
                <div id="settings-tab" class="tab-content hidden">
                    <div class="space-y-6">
                        <!-- 基本信息 -->
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 mb-6">
                                <i class="fas fa-user text-blue-600 mr-2"></i>基本信息
                            </h3>
                            <form id="profileForm" class="space-y-4">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label for="profileUsername" class="block text-sm font-medium text-gray-700 mb-2">用户名</label>
                                        <input type="text" id="profileUsername" name="username" 
                                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                               value="{{ current_user.username if current_user else '' }}">
                                    </div>
                                    <div>
                                        <label for="profileEmail" class="block text-sm font-medium text-gray-700 mb-2">邮箱地址</label>
                                        <input type="email" id="profileEmail" name="email" 
                                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                               value="{{ current_user.email if current_user else '' }}">
                                    </div>
                                </div>
                                <div>
                                    <label for="profileBio" class="block text-sm font-medium text-gray-700 mb-2">个人简介</label>
                                    <textarea id="profileBio" name="bio" rows="3" 
                                              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                              placeholder="介绍一下您自己..."></textarea>
                                </div>
                                <div class="flex justify-end">
                                    <button type="submit" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                        <i class="fas fa-save mr-2"></i>保存更改
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- 通知设置 -->
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 mb-6">
                                <i class="fas fa-bell text-blue-600 mr-2"></i>通知设置
                            </h3>
                            <div class="space-y-4">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-medium text-gray-900">邮件通知</p>
                                        <p class="text-sm text-gray-500">接收重要更新和通知</p>
                                    </div>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                    </label>
                                </div>
                                
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-medium text-gray-900">工具评论通知</p>
                                        <p class="text-sm text-gray-500">有人评论您的工具时通知</p>
                                    </div>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" class="sr-only peer" checked>
                                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 安全设置标签页 -->
                <div id="security-tab" class="tab-content hidden">
                    <div class="space-y-6">
                        <!-- 修改密码 -->
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 mb-6">
                                <i class="fas fa-key text-blue-600 mr-2"></i>修改密码
                            </h3>
                            <form id="passwordForm" class="space-y-4">
                                <div>
                                    <label for="currentPassword" class="block text-sm font-medium text-gray-700 mb-2">当前密码</label>
                                    <input type="password" id="currentPassword" name="current_password" 
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label for="newPassword" class="block text-sm font-medium text-gray-700 mb-2">新密码</label>
                                    <input type="password" id="newPassword" name="new_password" 
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label for="confirmNewPassword" class="block text-sm font-medium text-gray-700 mb-2">确认新密码</label>
                                    <input type="password" id="confirmNewPassword" name="confirm_new_password" 
                                           class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </div>
                                <div class="flex justify-end">
                                    <button type="submit" class="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
                                        <i class="fas fa-key mr-2"></i>更新密码
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- 登录记录 -->
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 mb-6">
                                <i class="fas fa-history text-blue-600 mr-2"></i>最近登录记录
                            </h3>
                            <div class="space-y-3">
                                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                    <div class="flex items-center">
                                        <div class="flex-shrink-0 w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                                            <i class="fas fa-desktop text-green-600 text-sm"></i>
                                        </div>
                                        <div class="ml-3">
                                            <p class="text-sm font-medium text-gray-900">Windows Chrome</p>
                                            <p class="text-sm text-gray-500">IP: 192.168.1.100</p>
                                        </div>
                                    </div>
                                    <div class="text-sm text-gray-500">
                                        <span class="text-green-600">当前会话</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 标签页切换
function showTab(tabName, event) {
    // 隐藏所有标签页内容
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.add('hidden');
    });
    
    // 显示选中的标签页
    document.getElementById(tabName + '-tab').classList.remove('hidden');
    
    // 更新导航样式
    document.querySelectorAll('.nav-item').forEach(item => {
        item.className = 'nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-700 hover:bg-gray-100';
    });
    
    // 只有在有事件对象时才更新点击的导航项样式
    if (event && event.target) {
        event.target.className = 'nav-item flex items-center px-3 py-2 text-sm font-medium rounded-lg text-blue-600 bg-blue-50 border border-blue-200';
    }
}

// 文件上传处理
function handleFileSelect(input) {
    const file = input.files[0];
    if (file) {
        if (file.type !== 'text/html') {
            alert('请选择HTML文件');
            input.value = '';
            return;
        }
        
        if (file.size > 10 * 1024 * 1024) { // 10MB
            alert('文件大小不能超过10MB');
            input.value = '';
            return;
        }
        
        document.getElementById('uploadPlaceholder').classList.add('hidden');
        document.getElementById('uploadPreview').classList.remove('hidden');
        document.getElementById('fileName').textContent = file.name;
        document.getElementById('fileSize').textContent = formatFileSize(file.size);
    }
}

function clearFile() {
    document.getElementById('htmlFile').value = '';
    document.getElementById('uploadPlaceholder').classList.remove('hidden');
    document.getElementById('uploadPreview').classList.add('hidden');
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 拖拽上传
const uploadArea = document.querySelector('.upload-area');

uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('border-blue-400', 'bg-blue-50');
});

uploadArea.addEventListener('dragleave', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('border-blue-400', 'bg-blue-50');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('border-blue-400', 'bg-blue-50');
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
        document.getElementById('htmlFile').files = files;
        handleFileSelect(document.getElementById('htmlFile'));
    }
});

// 表单提交
document.getElementById('uploadForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const uploadBtn = document.getElementById('uploadBtn');
    const uploadText = document.getElementById('uploadText');
    const uploadLoading = document.getElementById('uploadLoading');
    
    // 显示加载状态
    uploadBtn.disabled = true;
    uploadText.classList.add('hidden');
    uploadLoading.classList.remove('hidden');
    
    fetch('{{ url_for("upload_tool") }}', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('Upload response status:', response.status);
        console.log('Upload response ok:', response.ok);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.text().then(text => {
            console.log('Upload response text:', text);
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON parse error:', e);
                throw new Error('Invalid JSON response');
            }
        });
    })
    .then(data => {
        console.log('Upload response data:', data);
        if (data.success) {
            showSuccessMessage('工具上传成功！');
            resetForm();
            // 刷新我的工具列表
            refreshTools();
            // 切换到我的工具标签页
            showTab('tools');
        } else {
            showErrorMessage(data.message || '上传失败，请重试');
        }
    })
    .catch(error => {
        console.error('Upload error:', error);
        showErrorMessage('上传失败：' + error.message);
    })
    .finally(() => {
        uploadBtn.disabled = false;
        uploadText.classList.remove('hidden');
        uploadLoading.classList.add('hidden');
    });
});

function resetForm() {
    document.getElementById('uploadForm').reset();
    clearFile();
}

function refreshTools() {
    fetch('/api/my_tools')
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            displayTools(data.tools);
        } else {
            showErrorMessage(data.message || '获取工具列表失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showErrorMessage('获取工具列表失败，请重试');
    });
}

function displayTools(tools) {
    const toolsList = document.getElementById('toolsList');
    
    if (tools.length === 0) {
        toolsList.innerHTML = `
            <div class="text-center py-12">
                <i class="fas fa-tools text-4xl text-gray-300 mb-4"></i>
                <p class="text-gray-500">暂无上传的工具</p>
                <button onclick="showTab('upload', event)" class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                    <i class="fas fa-plus mr-2"></i>上传第一个工具
                </button>
            </div>
        `;
        return;
    }
    
    let toolsHtml = '';
    tools.forEach(tool => {
        const createdDate = new Date(tool.created_at).toLocaleDateString('zh-CN');
        toolsHtml += `
            <div class="bg-gray-50 rounded-lg p-4 border border-gray-200 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start mb-3">
                    <div class="flex-1">
                        <h4 class="font-semibold text-gray-900 mb-1">${tool.name}</h4>
                        <p class="text-sm text-gray-600 mb-2">${tool.description || '暂无描述'}</p>
                        <div class="flex items-center space-x-4 text-xs text-gray-500">
                            <span><i class="fas fa-tag mr-1"></i>${tool.category}</span>
                            <span><i class="fas fa-eye mr-1"></i>${tool.usage_count} 次访问</span>
                            <span><i class="fas fa-calendar mr-1"></i>${createdDate}</span>
                        </div>
                    </div>
                    <div class="flex space-x-2">
                        <a href="/tool/${tool.id}" target="_blank" class="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 transition-colors">
                            <i class="fas fa-external-link-alt mr-1"></i>访问
                        </a>
                        <button onclick="deleteTool(${tool.id})" class="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700 transition-colors">
                            <i class="fas fa-trash mr-1"></i>删除
                        </button>
                    </div>
                </div>
            </div>
        `;
    });
    
    toolsList.innerHTML = toolsHtml;
}

function deleteTool(toolId) {
    if (confirm('确定要删除这个工具吗？此操作不可恢复。')) {
        fetch(`/api/delete_tool/${toolId}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                showSuccessMessage('工具删除成功');
                refreshTools();
            } else {
                showErrorMessage(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showErrorMessage('删除失败，请重试');
        });
    }
}

function showSuccessMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

function showErrorMessage(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    alertDiv.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i>${message}`;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 页面加载时的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 加载统计数据
    loadStatistics();
    
    // 加载最近活动
    loadRecentActivity();
    
    // 加载热门工具
    loadPopularTools();
    
    // 加载工具列表
    refreshTools();
});

function loadStatistics() {
    // 这里应该从服务器获取统计数据
    // 暂时使用模拟数据
    document.getElementById('uploadedToolsCount').textContent = '0';
    document.getElementById('totalViews').textContent = '0';
    document.getElementById('totalLikes').textContent = '0';
}

function loadRecentActivity() {
    // 这里应该从服务器获取最近活动
    // 暂时显示默认内容
}

function loadPopularTools() {
    // 这里应该从服务器获取热门工具
    // 暂时显示默认内容
}
</script>
{% endblock %}